﻿using LinkPad.Shapes;
using Windows.Devices.Input;
using Windows.Foundation;
using Windows.UI.Xaml.Input;

namespace LinkPad.Handlers
{
    class PanHandler : CanvasActionHandler
    {
        #region Fields

        private Point _pressPoint;

        private double _pressViewLeft;
        private double _pressViewTop;

        private uint _penId;

        #endregion

        #region Constructors

        public PanHandler(ShapeManager shapeManager)
            : base(shapeManager)
        {
        }

        #endregion

        #region Properties

        #region CanvasActionHandler members

        public override bool HasColor
        {
            get { return false; }
        }

        #endregion

        #endregion

        #region Methods

        #region CanvasActionHandler members

        protected override void HandlePointerPressed(object sender, PointerRoutedEventArgs e)
        {
            var pt = e.GetCurrentPoint(MyCanvas);

            var pointerDevType = e.Pointer.PointerDeviceType;

            if (pointerDevType == PointerDeviceType.Pen ||
                pointerDevType == PointerDeviceType.Mouse &&
                pt.Properties.IsLeftButtonPressed
                || pointerDevType == PointerDeviceType.Touch)
            {
                _pressPoint = pt.Position;
                _penId = pt.PointerId;

                _pressViewLeft = ShapeManager.ViewLeft;
                _pressViewTop = ShapeManager.ViewTop;

                e.Handled = true;
            }

            base.HandlePointerPressed(sender, e);
        }

        protected override void HandlePointerMoved(object sender, PointerRoutedEventArgs e)
        {
            if (e.Pointer.PointerId == _penId)
            {
                var pt = e.GetCurrentPoint(MyCanvas);

                var currentPosition = pt.Position;

                var canvasWidth = MyCanvas.Width;
                var canvasHeight = MyCanvas.Height;
                var viewWidth = ShapeManager.ViewWidth;
                var viewHeight = ShapeManager.ViewHeight;
                var dx = _pressPoint.X - currentPosition.X;
                var dy = _pressPoint.Y - currentPosition.Y;
                dx *= viewWidth/canvasWidth;
                dy *= viewHeight/canvasHeight;

                ShapeManager.ViewAt(_pressViewLeft + dx, _pressViewTop + dy);

                e.Handled = true;
            }
            
            base.HandlePointerMoved(sender, e);
        }

        protected override void HandlePointerReleased(object sender, PointerRoutedEventArgs e)
        {
            _penId = 0;
            e.Handled = true;
            base.HandlePointerReleased(sender, e);
        }

        #endregion

        #endregion
    }
}
